<template>
    <div class="app-container flex-cloumn">
        <el-form :model="queryParams" ref="queryRef" v-show="showSearch" label-width="68px">
            <el-row :gutter="12">
                <el-col :span="4">
                    <el-form-item label="日志类型">
                        <dictCombox v-model="queryParams.logType" dictType="logType" size="small" :style="{width:'100%'}"
                                    @change="handleQuery"></dictCombox>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item :label-width="labelWidth" label="标的" prop="instrument">
                        <Underlyer ref="underlyerIdRef" v-model="queryParams.instrument" :style="{width:'100%'}"
                                   :underlyerId="queryParams.instrument"/>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="开始日期">
                        <el-date-picker
                                v-model="queryParams.begDate"
                                :style="{width:'100%'}"
                                placeholder="选择操作开始日期"
                                :disabled-date="disabledDateBeg"
                                size="small"
                                type="date"
                                value-format="YYYY-MM-DD">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="结束日期">
                        <el-date-picker
                                v-model="queryParams.endDate"
                                :style="{width:'100%'}"
                                placeholder="选择操作结束日期"
                                :disabled-date="disabledDateEnd"
                                size="small"
                                type="date"
                                value-format="YYYY-MM-DD">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="期权类型">
                        <dictCombox v-model="queryParams.optionType" dictType="optionType" :style="{width:'100%'}"
                                    size="small"></dictCombox>
                    </el-form-item>
                </el-col>

            </el-row>
            <el-row :gutter="12">
                <el-col :span="4">
                    <el-form-item label="交易对手" prop="partyId">
                        <baseCombox v-model="queryParams.partyId" clearable
                                    labelField="partyName"
                                    placeholder="交易对手"
                                    :style="{width:'100%'}"
                                    size="small" url="/trade/counterparty/queryCounterparty4Combox.action" valueField="partyId"
                                    @keyup.enter="handleQuery"></baseCombox>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="备注" prop="remark">
                        <el-input
                                v-model="queryParams.remark"
                                clearable
                                size="small"
                                :style="{width:'100%'}"
                                @keyup.enter="handleQuery"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item>
                        <el-button icon="Search" size="small" type="primary" style="margin: 3px 3px"
                                   v-hasPermi="['calc:otcOtion:pricingdraft:list']" @click="handleQuery">搜索
                        </el-button>
                        <el-button
                                v-hasPermi="['calc:otcOtion:pricingdraft:remove']"
                                :disabled="single"
                                style="margin: 3px 3px"
                                icon="Delete"
                                size="small"
                                type="danger"
                                @click="handleDelete"
                        >删除
                        </el-button>
                        <el-button icon="edit" size="small" type="primary" style="margin: 3px 3px" :disabled="single"
                                   v-hasPermi="['calc:otcOtion:pricingdraft:reCal']" @click="reCal">定价
                        </el-button>
                    </el-form-item>
                </el-col>
            </el-row>

        </el-form>

        <xTable ref="draftRef" v-loading="loading"
                :data="draftList"
                class="tableDragger_form"
                multiple="false"
                refId="draftRef"
                @selection-change="handleSelectionChange" @row-dblclick="handleDbclick">
            <template #columList>
                <el-table-column label="序号" type="index" width="60"/>
                <el-table-column :show-overflow-tooltip="true" align="center" label="日志ID" prop="id"/>
                <el-table-column v-if="queryParams.logType=='1'" :show-overflow-tooltip="true" align="center" label="草稿名称"
                                 prop="draftName"/>
                <el-table-column :show-overflow-tooltip="true" align="center" label="期权类型" prop="optionType" width="100">
                    <template #default="scope">
                        <dict-tag :options="optionType" :value="scope.row.optionType"/>
                    </template>
                </el-table-column>
                <el-table-column :show-overflow-tooltip="true" align="left" label="标的代码" prop="iCode"/>
                <el-table-column :show-overflow-tooltip="true" align="left" label="标的名称" prop="iName"/>
                <el-table-column v-if="false" :show-overflow-tooltip="true" align="center" label="交易对手" prop="partyId"/>
                <el-table-column :show-overflow-tooltip="true" align="center" label="交易对手" prop="partyName"
                                 v-if="queryParams.logType=='1'"/>
                <el-table-column v-if="false" align="center" label="计算类型" prop="calcType"/>
                <el-table-column align="right" label="计算日期" prop="valueDate"/>
                <el-table-column align="right" label="操作日期" prop="operateDate"/>
                <el-table-column align="right" label="操作时间" prop="reqTime" v-if="queryParams.logType!='1'"/>
                <el-table-column :show-overflow-tooltip="true" align="center" label="备注" v-if="queryParams.logType=='1'"
                                 prop="remark"/>
                <el-table-column align="center">
                    <template #default="scope">
                        <el-button size="small" @click="openDetail(scope.$index, scope.row)"
                        >详情
                        </el-button>
                    </template>
                </el-table-column>
            </template>
        </xTable>
        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 草稿、日志详细   -->
        <el-dialog v-model="InstrumentDialogVisible" :title="queryParams.logType=='1'?'草稿详情':'日志详情'" width="380px"
                   destroy-on-close :close-on-click-modal="false">
            <detail :close="closeInstrumentDialog" :instrument="InstrumentDialogInstrument.data"/>
        </el-dialog>
    </div>
</template>

<script setup name="PricingDraft">
import Underlyer from '@/xquant/base/underlyer'
import xTable from '@/xquant/base/xTable'
import detail from './detail.vue'
import {formartFormP2, unFormartNumber, numberPrecision} from '@/utils/numberUtil'
import {calcAnnualizedByTerminationPaymentDate } from '@/utils/util'
import {deleteCalcLogs, getCalcLogs} from '@/api/calc/otcOption/calc'

const store = useStore();
//转驼峰
const camelCase = (str) => {
    return str.replace(/-(\w)/g, function (all, letter) {
        return letter.toUpperCase()
    })
}
const router = useRouter()
const {proxy} = getCurrentInstance()
const {
    M_TYPE,
    A_TYPE,
    CURRENCY,
    optionType,
    logType
} = proxy.useDict('M_TYPE', 'A_TYPE', 'CURRENCY', 'optionType', 'logType')
const screenHeight = ref(document.documentElement.clientHeight - 250 + 'px')
const draftList = ref([])
const showSearch = ref(true)
const loading = ref(true)
const ids = ref([])
const rows = ref([])
const indexs = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const data = reactive({
    queryParams: {
        pageNum: 1,
        pageSize: 20,
        instrument: undefined,
        calcType: null,
        partyId: null,
        remark: null,
        logType: '1',
        begDate: '',
        endDate: '',
    }
})
const InstrumentDialogVisible = ref(false)
const InstrumentDialogInstrument = reactive({})
const selectRows = reactive({
    data: []
})

const {queryParams} = toRefs(data)

const disabledDateBeg = (time) => {
    if (queryParams.value.endDate) {
        return time.getTime() > new Date(queryParams.value.endDate).getTime()
    }
}

const disabledDateEnd = (time) => {
    if (queryParams.value.begDate) {
        return time.getTime() < new Date(queryParams.value.begDate).getTime() - 86400000
    }
}

function handleQuery() {
    getList()
}

function closeInstrumentDialog() {
    InstrumentDialogVisible.value = false
}

function reCal() {
    if (selectRows.data.length > 0) {
        let {pForm, pFormPricing, pFormInstrument, draftName, optionType, id, pFormResult, pResponse,valueDate} = selectRows.data[0]
        let pFormResultJson = pFormResult
        pForm = {...JSON.parse(pForm),...{'calcPricingParam':{'valueDate':valueDate}}}
        if (pFormResult == null) {
            let form = JSON.parse(pFormInstrument)
            let result = JSON.parse(String(pResponse)).result
            if (result != undefined && result.errorCode != '-1') {
                let other = {
                    'npvPercentage': formartFormP2(100 * result.contract.npv / form.notional),
                    'yearnpvPercentage': formartFormP2(100 * result.contract.npv / form.notional * calcAnnualizedByTerminationPaymentDate(form)),
                    'gammacash': formartFormP2(result.contract.gamma * result.contract.spotPrice * result.contract.spotPrice / 100),
                    'deltacash': formartFormP2(result.contract.delta * result.contract.spotPrice)
                }
                pFormResultJson = JSON.stringify(Object.assign(result.contract, other))
            }
        }
        store.commit("RM_Map", id)
        router.push({
            path: '/calc/OtcOptionRef/index/' + id,
            query:
                {
                    'dataId':id,
                    'dictId': draftName,
                    'pForm': JSON.stringify(pForm),
                    'pFormInstrument': pFormInstrument,
                    'pFormPricing': pFormPricing,
                    'productType': optionType,
                    'pFormResult': pFormResultJson,
                    title: '试算重现:' + (draftName ? draftName : JSON.parse(pFormInstrument).iCode),
                    showTitleDetail: '试算重现' + (draftName ? draftName : JSON.parse(pFormInstrument).iCode)
                },
        })
    }
}

/** 查询列表 */
function getList() {
    loading.value = true
    getCalcLogs(queryParams.value).then(response => {
        draftList.value = response.rows
        total.value = response.total
        loading.value = false
    })
}

/** 删除 */
function handleDelete() {
    loading.value = true
    var params = {}
    params.id = rows.value[0].id
    proxy.$modal.confirm('确认要删除吗？').then(function () {
        deleteCalcLogs(params).then(response => {
            getList()

        })
    }).then(function () {
        loading.value = false
    }).catch(function () {
        loading.value = false
    })
}


// 多选框选中
function handleSelectionChange(selection) {
    selectRows.data = [selection[0]]
    if (selection.length == 0) {
        ids.value = []
        indexs.value = []
        rows.value = []
    } else {
        ids.value = selection.map(item => item.id)
        indexs.value = selection.map(item => item.index)
        rows.value = selection.map(item => item)
    }
    single.value = selection.length != 1
    multiple.value = !selection.length
    if (selection.length == 1) {
        single.value = false
        return
    }
    if (selection.length != 1) {
        single.value = true
    }
}

function handleDbclick(row, column, event) {
    let {pForm, pFormPricing, pFormInstrument, draftName, optionType, id, pFormResult, pResponse} = row
    InstrumentDialogInstrument.data = {pForm, pFormPricing, pFormInstrument, draftName, optionType, id}
    let pFormResultJson = pFormResult
    if (pFormResult == null) {
        let form = JSON.parse(pFormInstrument)
        let result = JSON.parse(String(pResponse)).result
        if (result != undefined) {
            let other = {
                'npvPercentage': formartFormP2(100 * result.contract.npv / form.notional),
                'yearnpvPercentage': formartFormP2(100 * result.contract.npv / form.notional * calcAnnualizedByTerminationPaymentDate(form)),
                'gammacash': formartFormP2(result.contract.gamma * result.contract.spotPrice * result.contract.spotPrice / 100),
                'deltacash': formartFormP2(result.contract.delta * result.contract.spotPrice)
            }
            pFormResultJson = JSON.stringify(Object.assign(result.contract, other))
        }
    }
    InstrumentDialogInstrument.data.pFormResult = pFormResultJson
    InstrumentDialogVisible.value = true
}

function openDetail(index, row) {
    handleDbclick(row)
}

getList()
onMounted(() => {
    setTimeout(() => {
        loading.value = false
    }, 300)
    window.onresize = function temp() {
        screenHeight.value = document.documentElement.clientHeight - 250 + 'px;'
    }
})

</script>
